import { defer } from "@/utils/defer";
import axios from "axios";
import { ElButton, ElDialog, ElInput, ElTable, ElTableColumn } from "element-plus";
import { createApp, defineComponent, getCurrentInstance, reactive } from "vue";
import { events } from "./events";

// 表格新增表单   表单数据从哪里来？
const ServiceComponent = defineComponent({
  props: {
    option: {
      type: Object,
    },
  },
  setup(props) {
    const ctx = getCurrentInstance();
    const state = reactive({
      option: props.option,
      showFlag: false, // 是否显示
      mounted: (async () => {
        // 异步加载初始化
      })(),
      formField: [], // 表单字段
      editorData: [], // 表单数据
    });

    const methods = {
      service: (option) => {
        state.option = option;
        methods.init();
        methods.show();
      },
      init: async () => {
        // 请求后端表单数据
        let d = await axios.get("http://localhost:8010/api/user/meta/form?formId=24");
        let formParam = d.data.data.form_param;
        // 表单的字段
        let fieldList = formParam.templateContainerList[0].fieldList;
        // 字段转换
        state.formField = fieldList.map((d) => {
          return { field: d.propertyName, label: d.title };
        });
        console.log("form:", state.formField);
      },
      show: async () => {
        await state.mounted;
        state.showFlag = true;
      },
      hide: async () => {
        state.showFlag = false;
      },
      add: () => {
        console.log("form2:", state.formField);
        state.editorData.push({});
      },
    };

    const hanlder = {
      // 提交处理
      onConfirm: async () => {
        let data = await axios.post("http://localhost:8010/api/user/create", state.editorData);
        if (data && data.status == 200) {
          // 发送一个事件
          events.emit("refresh");
          methods.hide();
        }
      },
      onCancel: () => {
        methods.hide();
      },
      onDelete: (index) => {
        state.editorData.splice(index, 1);
      },
    };

    Object.assign(ctx.proxy, methods);

    return () => (
      <ElDialog v-model={state.showFlag}>
        {{
          default: () => (
            <div>
              <div>
                <ElButton onClick={methods.add}>添加</ElButton>
              </div>
              <ElTable data={state.editorData}>
                <ElTableColumn type="index" />

                {state.formField.map((item, index) => (
                  <ElTableColumn label={item.label}>
                    {{
                      default: ({ row }) => <ElInput v-model={row[item.field]} />,
                    }}
                  </ElTableColumn>
                ))}

                <ElTableColumn label="操作栏">
                  {{
                    default: ({ $index }) => (
                      <ElButton type="danger" onClick={() => hanlder.onDelete($index)}>
                        删除
                      </ElButton>
                    ),
                  }}
                </ElTableColumn>
              </ElTable>
            </div>
          ),
          footer: () => (
            <>
              <ElButton onClick={hanlder.onCancel}>取消</ElButton>
              <ElButton type="primary" onClick={hanlder.onConfirm}>
                确定
              </ElButton>
            </>
          ),
        }}
      </ElDialog>
    );
  },
});

export const $$tablePropAdd = (() => {
  let ins; // 当前弹层实例
  return (option) => {
    if (!ins) {
      const el = document.createElement("div");
      document.body.appendChild(el);
      const app = createApp(ServiceComponent, { option });
      ins = app.mount(el);
    }
    const dfd = defer();
    ins.service({
      ...option,
      onConfirm: dfd.resolve,
    });
    return dfd.promise;
  };
})();
